/**  
 * @Title: GoodsServiceImpl.java
 * @Package com.silverbox.sweeporder.service.index.impl
 * @author litao
 * @date 2018年1月17日
 */
package com.silverbox.sweeporder.service.index.impl;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.google.gson.annotations.Until;
import com.silverbox.core.util.CalendarUtil;
import com.silverbox.shopper.entity.*;
import com.silverbox.shopper.entity.extend.*;
import com.silverbox.shopper.entity.extend.GoodsGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.DishRecommend;
import com.alipay.api.request.KoubeiCateringDishRecommendQueryRequest;
import com.alipay.api.response.KoubeiCateringDishRecommendQueryResponse;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.core.util.DateUtils;
import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.shopper.dubboApi.goods.ShopperGoodsServiceApi;
import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.sweeporder.common.AlipayServiceEnvConstants;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.common.util.KeyGenerateRulesUtils;
import com.silverbox.sweeporder.common.util.SweepOrderUtils;
import com.silverbox.sweeporder.controller.index.entryvo.KoubeiRecomEntryVO;
import com.silverbox.sweeporder.controller.index.entryvo.NeedGoodsAddCart;
import com.silverbox.sweeporder.controller.index.vo.CategoryGoodsVO;
import com.silverbox.sweeporder.controller.index.vo.CopyGoodsVO;
import com.silverbox.sweeporder.controller.index.vo.DiscountInfoVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsAndSizeVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsCookingVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsFeedVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsPractVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsPropsCVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsPropsVO;
import com.silverbox.sweeporder.controller.index.vo.GoodsVO;
import com.silverbox.sweeporder.controller.index.vo.GroupPackageGoodsVO;
import com.silverbox.sweeporder.controller.index.vo.GroupPackageSuitVO;
import com.silverbox.sweeporder.controller.index.vo.GroupPackageVO;
import com.silverbox.sweeporder.controller.index.vo.KoubeiRecommendGoodsVO;
import com.silverbox.sweeporder.controller.index.vo.OrdinaryPackageCVO;
import com.silverbox.sweeporder.controller.index.vo.OrdinaryPackageVO;
import com.silverbox.sweeporder.controller.index.vo.QrcodeGoodsVO;
import com.silverbox.sweeporder.controller.index.vo.ShopperConfigExtend;
import com.silverbox.sweeporder.controller.index.vo.ShopperGoodsVO;
import com.silverbox.sweeporder.controller.index.vo.SizePriceVO;
import com.silverbox.sweeporder.service.index.GoodsService;
import com.silverbox.sweeporder.service.redis.RedisService;
import com.silverbox.waimai.dubboApi.goodscart.GoodsCartServiceApi;
import com.silverbox.waimai.dubboApi.order.WaimaiServiceApi;
import com.silverbox.waimai.entity.GoodsCart;
import com.silverbox.waimai.entity.Waimai;
import com.silverbox.waimai.entity.extend.AlreadyGoods;
import com.silverbox.waimai.entity.extend.CopyGoods;
import com.silverbox.waimai.entity.extend.GoodsCartAndDetail;
import com.silverbox.waimai.entity.extend.GoodsCartExtend;
import com.silverbox.waimai.entity.extend.WaimaiParam;

/**
 * ClassName: GoodsServiceImpl
 * 
 * @author litao
 * @date 2018年1月17日
 */
@Service
//@Transactional
public class GoodsServiceImpl implements GoodsService {

	private static Logger logger = LoggerFactory.getLogger(GoodsServiceImpl.class);

	@Autowired
	private ShopperGoodsServiceApi shopperGoodsServiceApi;

	@Autowired
	private WaimaiServiceApi waimaiServiceApi;

	@Autowired
	private ShopperInfoServiceApi shopperInfoServiceApi;
	
	@Autowired
	private GoodsCartServiceApi goodsCartServiceApi;

	@Autowired
	private RedisService<Serializable, Object> redisService;
	
	@Value("${sweepOrder.APP_ID}")
	private String SWEEP_APP_ID;

	@Value("${server.url}")
	private String serverUrl;
	
	@Value("${default.hotGoodNum}")
	private String hotGoodNum;
	
	@Value("${default.styleHotGoodNum}")
	private String styleHotGoodNum;
	
	@Override
	public CoreResponse<ShopperGoodsVO> getShopperGoodsInfo(Integer shopperId, Integer storeId, String shopId,
			Long machineId, String tableUid, Integer clientOrderMode,Integer clientType,String appointmentTime,String reserveDate) throws ParseException {
		CoreResponse<ShopperGoodsVO> res = new CoreResponse<ShopperGoodsVO>();
		//获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//获取redis店铺白名单配置信息
		Object shopperWhite = redisService.getObj(storeId+"_shopperWhite");
		//后台redis配置开启，先查询redis中的商品   2020年1月8日15:23:59 by zjq
		String goodsKey = KeyGenerateRulesUtils.generateSweepShopGoodsKey(shopperId, storeId);
		if(null!=shopperConfigExt && new Integer(1).equals(shopperConfigExt.getSweepRedis())){
			//查询商品的redis
			Object redisGoodsObj = redisService.getObj(goodsKey);
			if(!Utils.isEmpty(redisGoodsObj)){
				res = JSONObject.parseObject(JSON.toJSONString(redisGoodsObj, SerializerFeature.WriteMapNullValue), CoreResponse.class);
				//res = JSONObject.parseObject(JSON.toJSONString(redisGoodsObj), CoreResponse.class);
				//logger.info("从redis中取商品数据");
				return res;
			}
		}
		// 查询是否先付后吃模式
		Integer isFirstPay = shopperConfigExt.getFirstPayMent();
		// 查询是否开启预约配送 
		Integer reserveTime = shopperConfigExt.getReserveTime();
		//查询是否开启商品默认规格显示
//        Integer isGoodsSizeDefault=shopperConfigExt.getIsGoodsSizeDefaultShow();
		//获取装修平台扫码、在线
		int decorationType = 0;
		// 在线订单 不显示称重商品
		if (Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)
            || Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(clientOrderMode)) {
			isFirstPay = 1;
			decorationType = 1;
		}
        Integer openSaleInteral=null;
        List<CategoryGoods> goodsList=null;
     /*   List<GroupGoodsExtend> groupGoodsList = null;
		if(!Utils.isEmpty(cookId) && !"0".equals(cookId)){
			// 获取菜谱中菜品
			groupGoodsList = shopperGoodsServiceApi.getGroupGoodsList(Integer.valueOf(cookId));
		}*/
        // 售罄时间
        String dateStart = DateUtils.getTodayStartTime();
        String dateEnd = DateUtils.getTodayEndTime();
        String nowDate = DateUtils.getNowTime();
        //查询店铺是否有 有效菜谱
        int isEffectGoodsGroup= shopperGoodsServiceApi.isEffectGoodsGroup(storeId,shopperId);
        List<GoodsGroup> groupList=null;
		if (isEffectGoodsGroup>0){
		    //查询子店铺 扫码点餐有效菜谱
            groupList=shopperGoodsServiceApi.getEffsctGroupByStoreId(storeId, shopperId);
            //日期对比
            groupList=dateTimecontrast(groupList);
            if (CollectionUtils.isEmpty(groupList)){
                //主账号分配的 扫码点餐菜谱
                groupList=shopperGoodsServiceApi.getEffsctGroupByShopperId(storeId,shopperId);
                groupList=dateTimecontrast(groupList);
                if (CollectionUtils.isEmpty(groupList)){
                    //子账号创建的 全部类型菜谱
                    groupList=shopperGoodsServiceApi.getDefaultGroupByStoreId(storeId, shopperId);
                    groupList=dateTimecontrast(groupList);
                    if (CollectionUtils.isEmpty(groupList)){
                        //主账号分配的 全部类型的菜谱
                        groupList=shopperGoodsServiceApi.getDefaultEffsctGroupByShopperId(storeId,shopperId);
                        groupList=dateTimecontrast(groupList);
                        if (CollectionUtils.isEmpty(groupList)){
                            //子账号 默认菜谱
                            groupList=shopperGoodsServiceApi.getDefaultGroup(storeId, shopperId);
                            groupList=dateTimecontrast(groupList);
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(groupList)){
                Integer groupId=groupList.get(0).getGroupId();
                redisService.setObj(storeId+"groupId",groupId);
                Integer storeIdGroup=groupList.get(0).getStoreId();
                GoodsGroupParam goodsGroupParam =new GoodsGroupParam();
                goodsGroupParam.setStartDate(dateStart);
                goodsGroupParam.setEndDate(dateEnd);
                goodsGroupParam.setNowDate(nowDate);
                goodsGroupParam.setShopperId(shopperId);
                goodsGroupParam.setGroupId(groupId);
                if (storeIdGroup!=null && shopperId!=null){
                    //子账号下菜谱详情
                    goodsGroupParam.setStoreId(storeIdGroup);
                    goodsList=shopperGoodsServiceApi.getEffsctGoodsGroupByStoreId(goodsGroupParam);
                }else {
                	goodsGroupParam.setStoreId(storeId);
                    goodsList=shopperGoodsServiceApi.getEffsctGoodsGroupByShopperId(goodsGroupParam);
                }
            }
        }else {
            // 查询是否开启分时段售卖
            openSaleInteral = shopperConfigExt.getOpenSaleInteral();
            GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
            goodsExtendParam.setShopperId(shopperId);
            goodsExtendParam.setStoreId(storeId);
            if (null != machineId) {
                goodsExtendParam.setMachineId(machineId);
            }
            goodsExtendParam.setIsFirstPay(isFirstPay);
            goodsExtendParam.setStartDate(dateStart);
            goodsExtendParam.setEndDate(dateEnd);
            goodsExtendParam.setNowDate(nowDate);
            if (shopperWhite != null) {
                Map<String, Integer> whiteMap = (HashMap<String, Integer>) shopperWhite;
                if (whiteMap != null) {
                    goodsExtendParam.setStoreCategory(whiteMap.get("storeCategory"));
                }
            }
            // 查询店铺所有商品
            goodsList = shopperGoodsServiceApi.getCategoryGoods(goodsExtendParam);
           /* logger.info("=========查询店铺是否显示默认规格，isGoodsSizeDefault：" + isGoodsSizeDefault);
            if (isGoodsSizeDefault != null && isGoodsSizeDefault == 1) {
                //查询店铺所有商品（显示商品默认规格  默认规格字段是否添加）
                goodsList = shopperGoodsServiceApi.getGoodsDefaultSize(goodsExtendParam);
                logger.info("=======显示默认规格");
            } else {
                // 查询店铺所有商品
                goodsList = shopperGoodsServiceApi.getCategoryGoods(goodsExtendParam);
            }*/
        }
		// 商家自定义本周最火是否启用手动优先
		Integer hotLevel = shopperConfigExt.getHotLevel();
		// 商家自定义本周最火显示数量
		Integer hotQuantity = shopperConfigExt.getHotQuantity();

		ShopperGoodsVO shopperGoodsVO = new ShopperGoodsVO(); 
		List<CategoryGoodsVO> categoryGoodsVoList = new ArrayList<CategoryGoodsVO>();

		if (CollectionUtils.isEmpty(goodsList)) {
			res.setSubMsg("店铺商品为空");
			shopperGoodsVO.setCategoryGoods(categoryGoodsVoList);
			res.setData(shopperGoodsVO);
			return res;
		}
		List<DaypartingGoods> daypartingGoods = null;
		List<DaypartingGoods> daypartingGoodsList = new ArrayList<DaypartingGoods>();
		Map<String, DaypartingGoods> map = new HashMap<String,DaypartingGoods>();
		// 分时段售卖商品
		if (new Integer(1).equals(openSaleInteral)) {
			int weekNum = DateUtils.getDayofweek();
			if(new Integer(1).equals(reserveTime) && !StringUtils.isEmpty(appointmentTime) && !StringUtils.isEmpty(reserveDate)){
				nowDate = reserveDate + " " +appointmentTime.split("-")[1] + ":00";
				weekNum = DateUtils.getDayofweek(CalendarUtil.formatByTime(nowDate));
				daypartingGoods = shopperGoodsServiceApi.getDaypartingGoods(storeId, weekNum, nowDate);
			}else{
				daypartingGoods = shopperGoodsServiceApi.getDaypartingGoods(storeId, weekNum, nowDate);
			}
		}
		if(!Utils.isEmpty(daypartingGoods)){
			for(DaypartingGoods daypartingGood : daypartingGoods){
				String key = daypartingGood.getGoodsId()+"_"+daypartingGood.getSizeid();
				if(map.get(key) == null){
					map.put(key, daypartingGood);
				}
			}
		}
		
		map.forEach((k, v) -> {
			daypartingGoodsList.add(v);
        });
		
		// 本周热销
		List<HotGoodsWeek> hotList = new ArrayList<HotGoodsWeek>();
		List<HotGoodsWeek> hotGoodsWeekList = null;

		//商家自定义本周最火商品为0则不显示本周最火商品
		if(hotQuantity>0){

			// 查询是否存在本周最火商品
			hotList = shopperGoodsServiceApi.getOldHotGoodsWeek(storeId, DateUtils.getTodayStartTime(),
					DateUtils.getTodayEndTime());
			// 执行存储过程插入本周最火商品
			if (CollectionUtils.isEmpty(hotList)) {
				shopperGoodsServiceApi.updateHotByCallAble(storeId, shopperId,
						DateUtils.getDateChangeString(DateUtils.sevenDaysAgoTime()), DateUtils.getTodayStartTime());
			}
			//获取店铺是否开启风格二配置，如果开启则本周最火商品最多显示二十条数据
			boolean flag = shopperInfoServiceApi.getShopperRenovationStyleByStoreId(storeId,decorationType);
			if(flag){
				hotQuantity = Integer.valueOf(styleHotGoodNum);
			}else if(hotQuantity>20){
				hotQuantity = Integer.valueOf(hotGoodNum);
			}

			//获取本周最火商品
			hotGoodsWeekList = shopperGoodsServiceApi.getHotWeekGoods(storeId, hotLevel, hotQuantity);
		}

		// 今日特惠商品
		List<DiscountInfo> discountInfoList = new ArrayList<DiscountInfo>();
		//clientType=3表示微信扫码进入不获取今日特惠商品
		if (!StringUtils.isEmpty(shopId) && !new Integer(3).equals(clientType)) {
			discountInfoList = shopperGoodsServiceApi.getDiscountGoods(shopId,null,nowDate,DateUtils.getDayofweek());
		}

		// 获取店铺必选分类信息
		List<RequiredCategory> 	requiredCategoryList=null;
		if (Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(clientOrderMode) || Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode) || (Constants.clientOrderMode.SCAN_ORDER_MODE.getValue().equals(clientOrderMode) || !StringUtils.isEmpty(tableUid))){
			requiredCategoryList = shopperGoodsServiceApi.getRequiredCategory(storeId, shopperId,tableUid);
		}

		//获取店铺推荐菜信息
		List<RecommendGoods> recommendGoodsList = shopperGoodsServiceApi.getRecommendGoods(shopperId, storeId);

		List<GoodsVO> hotGoodsWeekDetailList = new ArrayList<GoodsVO>();
		List<GoodsVO> discountInfoDetailList = new ArrayList<GoodsVO>();
		List<GoodsVO> recommendGoodsDetailList = new ArrayList<GoodsVO>();

		Map<Long, CategoryGoodsVO> categoryGoodsMap = new HashMap<Long, CategoryGoodsVO>();
		// 开启分时段售卖匹配相应商品
		if (new Integer(1).equals(openSaleInteral) && !CollectionUtils.isEmpty(daypartingGoodsList)) {
			for (CategoryGoods categoryGoods : goodsList) {
				for (DaypartingGoods goods : daypartingGoodsList) {
					if (categoryGoods.getGoodsId().equals(goods.getGoodsId())
							&&  categoryGoods.getSizeId().equals(goods.getSizeid())) {
						// 组装商品数据
						installShopperGoodsVO(categoryGoods, hotGoodsWeekList, discountInfoList, hotGoodsWeekDetailList,
								discountInfoDetailList, categoryGoodsMap, categoryGoodsVoList, requiredCategoryList,recommendGoodsList,recommendGoodsDetailList);
					}
				}
			}
		} else {
			for (CategoryGoods categoryGoods : goodsList) {
				// 组装商品数据
				installShopperGoodsVO(categoryGoods, hotGoodsWeekList, discountInfoList, hotGoodsWeekDetailList,
						discountInfoDetailList, categoryGoodsMap, categoryGoodsVoList, requiredCategoryList,recommendGoodsList,recommendGoodsDetailList);
			}
		}


		if (!Utils.isEmpty(hotGoodsWeekDetailList)) {
			//本周最火商品按照销售量由高到底排序
			Collections.sort(hotGoodsWeekDetailList, new Comparator<GoodsVO>() {
				@Override
				public int compare(GoodsVO o1, GoodsVO o2) {
					if (o1.getSalesVolume() < o2.getSalesVolume()) {
						return 1;
					} else {
						return -1;
					}
				}
			});
			CategoryGoodsVO hotcategory = new CategoryGoodsVO();
			hotcategory.setCategoryId(-1L);
			hotcategory.setCategoryTab(-1L);
			hotcategory.setCategoryName("本周最火");
			hotcategory.setGoods(hotGoodsWeekDetailList);
			categoryGoodsVoList.add(hotcategory);
		}
		if (!Utils.isEmpty(discountInfoDetailList)) {
			CategoryGoodsVO discountCategory = new CategoryGoodsVO();
			discountCategory.setCategoryId(-2L);
			discountCategory.setCategoryTab(-2L);
			discountCategory.setCategoryName("今日特惠");
			discountCategory.setGoods(discountInfoDetailList);
			categoryGoodsVoList.add(discountCategory);
		}
		if (!Utils.isEmpty(recommendGoodsDetailList)) {
			CategoryGoodsVO recommendGoods = new CategoryGoodsVO();
			recommendGoods.setCategoryId(-4L);
			recommendGoods.setCategoryTab(-4L);
			recommendGoods.setCategoryName("推荐菜");
			recommendGoods.setGoods(recommendGoodsDetailList);
			categoryGoodsVoList.add(recommendGoods);
		}

		if (!CollectionUtils.isEmpty(requiredCategoryList) && !CollectionUtils.isEmpty(categoryGoodsVoList)) {
			// 将必选分类信息数据写入商品分类中
			for (RequiredCategory category : requiredCategoryList) {
				for (CategoryGoodsVO goodsVO : categoryGoodsVoList) {
					if (!Utils.isEmpty(category.getCategoryId()) && category.getCategoryId().equals(goodsVO.getCategoryId())) {
						goodsVO.setCategoryTab(-3L);
						goodsVO.setRequiredCategory(1);
						goodsVO.setCategoryId(category.getCategoryId());
						goodsVO.setCategoryName(category.getCategoryName());
						goodsVO.setDefaultNum(category.getDefaultAdd());
					}
				}
			}
		}

		//排序
		if(!CollectionUtils.isEmpty(categoryGoodsVoList)){
			Collections.sort(categoryGoodsVoList, new Comparator<CategoryGoodsVO>() {
				@Override
				public int compare(CategoryGoodsVO o1, CategoryGoodsVO o2) {
					if (o1.getCategoryTab() < 0) {
						return -1;
					} else {
						return 1;
					}
				}
			});
		}

		shopperGoodsVO.setCategoryGoods(categoryGoodsVoList);
		/*if(null!=categoryGoodsVoList && categoryGoodsVoList.size()>0){
		redisService.setObj(goodsKey,categoryGoodsVoList,5L,TimeUnit.MINUTES);
		}*/
		res.setData(shopperGoodsVO);
		//后台redis配置开启，将首页商品存放到redis中   2020年1月8日15:23:59 by zjq
		if(null!=shopperConfigExt && new Integer(1).equals(shopperConfigExt.getSweepRedis())){
			redisService.setObj(goodsKey,res,5L,TimeUnit.MINUTES);
		}
		//logger.info("从数据库中取商品数据");
		return res;
	}

	private  List<GoodsGroup> dateTimecontrast(List<GoodsGroup> groupList) throws ParseException {
        List<GoodsGroup> goodsList1=new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupList)){
            for (GoodsGroup goodsGroup : groupList){
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                Date date = dateFormat.parse(dateFormat.format(new Date()));
                Date dateFirst = dateFormat.parse(goodsGroup.getStartDate());
                Date dateLast = dateFormat.parse(goodsGroup.getEndDate());
                String time=timeFormat.format(new Date());
                String timeFirst=goodsGroup.getStartTime();
                String timeLast=goodsGroup.getEndTime();
                //开始日期在当天之后 或者 开始日期在当天之前
                if (dateFirst.after(date) || dateLast.before(date)) {
                    continue;
                } else {
                    if (time.indexOf(":")<0||timeFirst.indexOf(":")<0 ||timeLast.indexOf(":")<0){
                        //logger.error("时间格式不正确");
                        continue;
                    }else {
                        String[]array1 = timeFirst.split(":");
                        int t1 = Integer.valueOf(array1[0])*3600+Integer.valueOf(array1[1])*60+Integer.valueOf(array1[2]);
                        String[]array2 = timeLast.split(":");
                        int t2 = Integer.valueOf(array2[0])*3600+Integer.valueOf(array2[1])*60+Integer.valueOf(array2[2]);
                        String[]array3 = time.split(":");
                        int t3 = Integer.valueOf(array3[0])*3600+Integer.valueOf(array3[1])*60+Integer.valueOf(array3[2]);
                        if (t3>=t1 && t3<=t2){
                            String week= goodsGroup.getWeek();
                            //当前时间为星期几
                            String day=String.valueOf(Utils.dayForWeek(new Date()));
                            if (!Utils.isEmpty(week)){
                                //数据库查询的星期是否包含当前星期
                                if (!week.contains(day)) {
                                    continue;
                                }
                            }
                        }else {
                            continue;
                        }
                    }
                }
                goodsList1.add(goodsGroup);
            }
        }
        //logger.info("++++++++++++++++goodsList1:"+goodsList1.size());
	    return goodsList1;
    }

	/**
	 * 组装商品
	 * 
	 * @param categoryGoods
	 * @param hotGoodsWeekList
	 * @param discountInfoList
	 * @param hotGoodsWeekDetailList
	 * @param discountInfoDetailList
	 * @param categoryGoodsMap
	 * @param categoryGoodsVoList
	 * @return void
	 * @author litao
	 * @date 2018年1月18日
	 */
	private void installShopperGoodsVO(CategoryGoods categoryGoods, List<HotGoodsWeek> hotGoodsWeekList,
			List<DiscountInfo> discountInfoList, List<GoodsVO> hotGoodsWeekDetailList,
			List<GoodsVO> discountInfoDetailList, Map<Long, CategoryGoodsVO> categoryGoodsMap,
			List<CategoryGoodsVO> categoryGoodsVoList, List<RequiredCategory> requiredCategoryList, 
			List<RecommendGoods> recommendGoodsList, List<GoodsVO> recommendGoodsDetailList) {

		GoodsVO goods = conversionGoodsVO(categoryGoods);
		//商品是否属于必选分类下
		if(!CollectionUtils.isEmpty(requiredCategoryList)){
			for(RequiredCategory category:requiredCategoryList){
				if(!Utils.isEmpty(category.getCategoryId()) && category.getCategoryId().equals(goods.getCategoryId())){
					goods.setRequiredCategory(1);
				}
			}
		}
		
		// 组装本周最火商品
		if (!CollectionUtils.isEmpty(hotGoodsWeekList)) { 
			Iterator<HotGoodsWeek> hotIt = hotGoodsWeekList.listIterator();
			if (hotGoodsWeekDetailList.size() <= 20) {
				while (hotIt.hasNext()) {
					HotGoodsWeek hotGoodsWeek = hotIt.next();
					if (goods.getGoodsId().equals(hotGoodsWeek.getGoodsId())
							&& goods.getSizeId().equals(hotGoodsWeek.getSizeId())) {
						goods.setSalesVolume(hotGoodsWeek.getSalesVolume());
						goods.setGoodsTab(new Integer(-1));
						hotGoodsWeekDetailList.add(goods);
						hotIt.remove();
						break;
					}
				}
			}
		}

		if (!CollectionUtils.isEmpty(discountInfoList)) {
			// 组装折扣商品
			for (DiscountInfo discountInfo : discountInfoList) {
				if (goods.getGoodsId().equals(discountInfo.getGoodsId())) {
					DiscountInfoVO discountInfoVO = null;
					if (discountInfo != null) {
						discountInfoVO = new DiscountInfoVO();
						BeanUtils.copyProperties(discountInfo, discountInfoVO);
					}
					goods.setGoodsTab(new Integer(-2));
					goods.setDiscountInfo(discountInfoVO);
					discountInfoDetailList.add(goods);
					break;
				}
			}
		}
		
		// 组装商品分类
		CategoryGoodsVO obj = categoryGoodsMap.get(goods.getCategoryId());
		if (obj == null) {
			obj = new CategoryGoodsVO();
			obj.setCategoryId(goods.getCategoryId());
			obj.setCategoryTab(goods.getCategoryId());
			obj.setCategoryName(goods.getCategoryName());
			categoryGoodsMap.put(obj.getCategoryId(), obj);
			categoryGoodsVoList.add(obj);
		}
		
		//组装店铺推荐菜
		if (!CollectionUtils.isEmpty(recommendGoodsList)) {
			Iterator<RecommendGoods> recommendGoods = recommendGoodsList.listIterator();
			while (recommendGoods.hasNext()) {
				RecommendGoods recommendGood = recommendGoods.next();
					if (goods.getGoodsId().equals(recommendGood.getGoodsId())
							&& goods.getSizeId().equals(recommendGood.getSizeId())) {
						goods.setGoodsTab(new Integer(-4));
						recommendGoodsDetailList.add(goods);
						recommendGoods.remove();
						break;
					}
				}
		}
		
		obj.getGoods().add(goods);
	}

	@Override
	public Map<Integer, GoodsPropsCVO> getAllGoodsPropInfo(Integer storeId, Integer shopperId) {
		// 获取所有商品属性信息
		List<GoodsPropsExtend> goodsProps = shopperGoodsServiceApi.getAllGoodsBindPropsList(shopperId, storeId);
		// 获取所有商品加价信息
		List<GoodsPropsExtend> goodsCookings = shopperGoodsServiceApi.getAllGoodsCookingsList(shopperId);
		if (CollectionUtils.isEmpty(goodsProps) && CollectionUtils.isEmpty(goodsCookings)) {
			return null;
		}
		// 组装商品属性数据
		Map<Integer, GoodsPropsCVO> goodsPropsMap = installGoodsProps(goodsProps,goodsCookings);
		return goodsPropsMap;
	}

	/**
	 * 组装商品属性信息数据
	 * 
	 * @param goodsProps
	 * @return Map<Integer,GoodsPropsCVO>
	 * @author litao
	 * @param goodsCookings 
	 * @date 2018年1月10日
	 */
	private Map<Integer, GoodsPropsCVO>     installGoodsProps(List<GoodsPropsExtend> goodsProps, List<GoodsPropsExtend> goodsCookings) {
		// 定义所有商品属性的Map数据封装
		Map<Integer, GoodsPropsCVO> goodsPropsCVOMap = new HashMap<Integer, GoodsPropsCVO>();// 属性Map封装

		Map<String, GoodsPractVO> goodsPractVOMap = new HashMap<String, GoodsPractVO>();// 做法分类
		//加料分类分组       
		Map<String,GoodsFeedVO> goodsFeedVOMap = new HashMap<String,GoodsFeedVO>();
		//加价分组
		Map<String,GoodsCookingVO> goodsCookingVOMap = new HashMap<String,GoodsCookingVO>();

		Map<String,SizePriceVO>  goodsSizePriceVoMap=new HashMap<>();



		if(!CollectionUtils.isEmpty(goodsProps)){
			for (GoodsPropsExtend props : goodsProps) {
				// 是否存在商品
				GoodsPropsCVO goodsPropsCVO = goodsPropsCVOMap.get(props.getGoodsId());
				if (goodsPropsCVO == null) {
					goodsPropsCVO = new GoodsPropsCVO();
					goodsPropsCVO.setGoodsId(props.getGoodsId());
					goodsPropsCVOMap.put(props.getGoodsId(), goodsPropsCVO);
				}
				// 组装商品做法信息
				if (new Integer(5).equals(props.getPropCategoryTypeId())) {
					// 判断是否存在分类
					GoodsPractVO goodsPractVO = goodsPractVOMap.get(props.getGoodsId() + "_" + props.getPropCategoryId());
					if (goodsPractVO == null) {
						goodsPractVO = new GoodsPractVO();
						goodsPractVO.setPropCategoryId(props.getPropCategoryId());
						goodsPractVO.setPropCategoryName(props.getPropCategoryName());
						if (Utils.isEmpty(props.getIsMustOption())){
                            goodsPractVO.setIsMustOption(0);
                        }else {
                            goodsPractVO.setIsMustOption(props.getIsMustOption());
                        }
						goodsPractVO.setPropIsRadio(props.getPropIsRadio() == null ? 0 : props.getPropIsRadio());
						goodsPractVOMap.put(props.getGoodsId() + "_" + props.getPropCategoryId(), goodsPractVO);
						// 判断商品做法是否存在
						if (CollectionUtils.isEmpty(goodsPropsCVO.getGoodsPract())) {
							List<GoodsPractVO> goodsPractVOs = new ArrayList<GoodsPractVO>();
							goodsPropsCVO.setGoodsPract(goodsPractVOs);
						}
						goodsPropsCVO.getGoodsPract().add(goodsPractVO);
					}
					GoodsPropsVO goodsPropsVO = new GoodsPropsVO();
					BeanUtils.copyProperties(props, goodsPropsVO);
					goodsPractVO.getGoodsProps().add(goodsPropsVO);
					continue;
				}
				// 组装商品加料信息
				if (new Integer(1).equals(props.getPropCategoryTypeId())) {
					GoodsFeedVO goodsFeedVO = goodsFeedVOMap.get(props.getGoodsId()+"_"+props.getPropCategoryId());
					if(goodsFeedVO==null){
						goodsFeedVO = new GoodsFeedVO();
						goodsFeedVO.setPropCategoryId(props.getPropCategoryId());
						goodsFeedVO.setPropCategoryName(props.getPropCategoryName());
						goodsFeedVOMap.put(props.getGoodsId()+"_"+props.getPropCategoryId(), goodsFeedVO);
						// 判断商品加料是否存在
						if (CollectionUtils.isEmpty(goodsPropsCVO.getGoodsFeed())) {
							List<GoodsFeedVO> goodsPropsVOs = new ArrayList<GoodsFeedVO>();
							goodsPropsCVO.setGoodsFeed(goodsPropsVOs);
						}
						goodsPropsCVO.getGoodsFeed().add(goodsFeedVO);
					}
					GoodsPropsVO goodsFeed = new GoodsPropsVO();
					BeanUtils.copyProperties(props, goodsFeed);
					goodsFeedVO.getGoodsProps().add(goodsFeed);
				}
			}
		}

		//商品规格
      /* if (!CollectionUtils.isEmpty(goodsDetailList)){
            for (CategoryGoodsDetail goodsSize:goodsDetailList){
                GoodsPropsCVO goodsPropsCVO = goodsPropsCVOMap.get(goodsSize.getGoodsId());
                if (goodsPropsCVO==null){
                    goodsPropsCVO=new GoodsPropsCVO();
                    goodsPropsCVO.setGoodsId(goodsSize.getGoodsId());
                    goodsPropsCVOMap.put(goodsSize.getGoodsId(),goodsPropsCVO);
                }

                SizePriceVO sizePriceVO=goodsSizePriceVoMap.get(goodsSize.getGoodsId()+"_"+goodsSize.getSizeId());
                if (sizePriceVO==null){
                    sizePriceVO=new SizePriceVO();
                    sizePriceVO.setPrice(goodsSize.getPrice());
                    sizePriceVO.setSizeId(goodsSize.getSizeId());
                    sizePriceVO.setSizeType(goodsSize.getType());
                    goodsSizePriceVoMap.put(goodsSize.getGoodsId()+"_"+goodsSize.getSizeId(),sizePriceVO);
                    if (CollectionUtils.isEmpty(goodsPropsCVO.getGoodsSize())){
                        List<SizePriceVO> sizePriceVOS=new ArrayList<>();
                        goodsPropsCVO.setGoodsSize(sizePriceVOS);
                    }
                    goodsPropsCVO.getGoodsSize().add(sizePriceVO);
                }
            }
        }*/

		if(!CollectionUtils.isEmpty(goodsCookings)){
			for(GoodsPropsExtend cookings : goodsCookings){
				// 是否存在商品
				GoodsPropsCVO goodsPropsCVO = goodsPropsCVOMap.get(cookings.getGoodsId());
				if (goodsPropsCVO == null) {
					goodsPropsCVO = new GoodsPropsCVO();
					goodsPropsCVO.setGoodsId(cookings.getGoodsId());
					goodsPropsCVOMap.put(cookings.getGoodsId(), goodsPropsCVO);
				}
				//组装商品加价做法信息
				GoodsCookingVO goodsCookingVO = goodsCookingVOMap.get(cookings.getGoodsId()+"_"+cookings.getUuid());
				if(goodsCookingVO == null){
					goodsCookingVO = new GoodsCookingVO();
					goodsCookingVO.setCookingType(cookings.getCookingType());
					goodsCookingVO.setGcName(cookings.getGcName());
					goodsCookingVO.setPrice(cookings.getPrice());
					goodsCookingVO.setUuid(cookings.getUuid());
					goodsCookingVO.setPropIsRadio(cookings.getPropIsRadio());
					goodsCookingVO.setSelected(cookings.getSelected());
					goodsCookingVOMap.put(cookings.getGoodsId()+"_"+cookings.getUuid(), goodsCookingVO);
					// 判断商品加价做法是否存在
					if (CollectionUtils.isEmpty(goodsPropsCVO.getGoodsCooking())) {
						List<GoodsCookingVO> goodsCookingVOs = new ArrayList<GoodsCookingVO>();
						goodsPropsCVO.setGoodsCooking(goodsCookingVOs);
					}
					goodsPropsCVO.getGoodsCooking().add(goodsCookingVO);
				}
			}
		}
		return goodsPropsCVOMap;
	}

	public Map<Integer, OrdinaryPackageCVO> getAllNormalPackageGoods(Integer shopperId) {
		// 获取店铺所有普通套餐信息
		List<NormalPackage> normalPackage = shopperGoodsServiceApi.getNormalPackageList(shopperId);
		if (CollectionUtils.isEmpty(normalPackage)) {
			return null;
		}
		// 定义普通套餐数据封装
		Map<Integer, OrdinaryPackageCVO> OrdinaryPackages = new HashMap<Integer, OrdinaryPackageCVO>();
		// 组装普通套餐数据
		for (NormalPackage packages : normalPackage) {
			OrdinaryPackageCVO ordinaryPackage = OrdinaryPackages.get(packages.getGoodsId());
			if (ordinaryPackage == null) {
				ordinaryPackage = new OrdinaryPackageCVO();
				ordinaryPackage.setPackageId(packages.getGoodsId());
				// 判断普通套餐信息是否已存在
				if (CollectionUtils.isEmpty(ordinaryPackage.getOrdinaryPackages())) {
					List<OrdinaryPackageVO> ordinaryPackageVO = new ArrayList<OrdinaryPackageVO>();
					ordinaryPackage.setOrdinaryPackages(ordinaryPackageVO);
				}
				OrdinaryPackages.put(ordinaryPackage.getPackageId(), ordinaryPackage);
			}
			OrdinaryPackageVO ordinaryPackageVO = new OrdinaryPackageVO();
			BeanUtils.copyProperties(packages, ordinaryPackageVO);
			ordinaryPackage.getOrdinaryPackages().add(ordinaryPackageVO);
		}
		return OrdinaryPackages;
	}

	@Override
	public Map<Integer, GroupPackageVO> getGroupPackageGoodsById(Integer storeId, Integer shopperId) {
		// 获取所有组合套餐商品信息
		List<CombinationPackage> combinationPackages = shopperGoodsServiceApi.getCombinationPackageList(shopperId,
				storeId);
		if (CollectionUtils.isEmpty(combinationPackages)) {
			return null;
		}
		// 定义所有组合套餐数据
		Map<Integer, GroupPackageVO> groupPackage = new HashMap<Integer, GroupPackageVO>();
		// 定义分组下商品数据
		Map<String, GroupPackageSuitVO> groupPackageSuit = new HashMap<String, GroupPackageSuitVO>();

		for (CombinationPackage packages : combinationPackages) {
			// 判断是否存在套餐商品数据
			GroupPackageVO groupPackageVO = groupPackage.get(packages.getPackageId());
			if (groupPackageVO == null) {
				groupPackageVO = new GroupPackageVO();
				groupPackageVO.setPackageId(packages.getPackageId());
				groupPackage.put(packages.getPackageId(), groupPackageVO);
			}
			// 判断是否存在套餐的分组数据
			GroupPackageSuitVO groupPackageSuitVO = groupPackageSuit
					.get(packages.getPackageId() + "_" + packages.getSuitGroupId());
			if (groupPackageSuitVO == null) {

				groupPackageSuitVO = new GroupPackageSuitVO();
				groupPackageSuitVO.setSuitId(packages.getSuitGroupId());
				groupPackageSuitVO.setSuitName(packages.getSuitGroupName());
				groupPackageSuitVO.setSuitStartNumber(packages.getSuitStartNumber());
				groupPackageSuitVO.setSuitEndNumber(packages.getSuitEndNumber());
				groupPackageSuitVO.setSuitState(packages.getSuitState());
				groupPackageSuitVO.setSuitSort(packages.getSuitSort());

				groupPackageSuit.put(packages.getPackageId() + "_" + packages.getSuitGroupId(), groupPackageSuitVO);

				groupPackageVO.getGroupPackages().add(groupPackageSuitVO);
			}
			GroupPackageGoodsVO groupPackageGoods = new GroupPackageGoodsVO();
			BeanUtils.copyProperties(packages, groupPackageGoods);
			groupPackageSuitVO.getGroupGoods().add(groupPackageGoods);
		}
		return groupPackage;
	}

	private List<KoubeiRecommendGoodsVO> sort(List<KoubeiRecommendGoodsVO> list) {
		Collections.sort(list, new Comparator<KoubeiRecommendGoodsVO>() {
			public int compare(KoubeiRecommendGoodsVO o1, KoubeiRecommendGoodsVO o2) {
				return o1.getBuyPosibility() < o2.getBuyPosibility() ? 1
						: (o1.getBuyPosibility() == o2.getBuyPosibility() ? 0 : -1);
			}
		});
		return list;
	}

	/**
	 * 商品GoodsVO转换
	 * 
	 * @param categoryGoods
	 * @return GoodsVO
	 * @author litao
	 * @date 2018年1月18日
	 */
	private GoodsVO conversionGoodsVO(CategoryGoods categoryGoods) {
		GoodsVO goods = new GoodsVO();
		goods.setCategoryId(categoryGoods.getCategoryId());
		goods.setCategoryName(categoryGoods.getCategoryName());
		goods.setDescription(categoryGoods.getDescription());
		DiscountInfoVO discountInfo = null;
		if (null != categoryGoods.getDiscountInfo()) {
			discountInfo = new DiscountInfoVO();
			BeanUtils.copyProperties(categoryGoods.getDiscountInfo(), discountInfo);
		}
		goods.setDiscountInfo(discountInfo);
		goods.setGoodsId(categoryGoods.getGoodsId());
		goods.setGoodsName(categoryGoods.getGoodsName());
		goods.setImagePath(categoryGoods.getImagePath());
		goods.setIsPackage(categoryGoods.getIsPackage());
		goods.setIsSellOut(categoryGoods.getIsSellOut());
		goods.setIsWeight(categoryGoods.getIsWeight());
		goods.setPrice(categoryGoods.getPrice());
		goods.setSalesVolume(categoryGoods.getSalesVolume());
		goods.setSizeCount(categoryGoods.getSizeCount());
		goods.setSizeId(categoryGoods.getSizeId());
		goods.setSizeType(categoryGoods.getSizeType());
		goods.setGoodsSellNum(categoryGoods.getMinSell()==null?1:categoryGoods.getMinSell());
		goods.setGoodsAddNum(categoryGoods.getMinAddUnit()==null?1:categoryGoods.getMinAddUnit());
		goods.setSpicyName(categoryGoods.getSpicyName());
		goods.setSpicyValue(categoryGoods.getSpicyValue());
		goods.setSpicyImagePath(categoryGoods.getSpicyImagePath());
		goods.setMemberPrice(categoryGoods.getMemberPrice());
        goods.setOriginPrice(Utils.isEmpty(categoryGoods.getOriginPrice()) ? categoryGoods.getPrice() : categoryGoods.getOriginPrice());
		return goods;
	}

	@Override
	public CoreResponse<List<GoodsPractVO>> getShopperPropInfo(Integer shopperId, Integer storeId) {

		CoreResponse<List<GoodsPractVO>> res = new CoreResponse<List<GoodsPractVO>>();

		List<GoodsPropsExtend> goodsProps = shopperGoodsServiceApi.getShopBindPropsList(shopperId, storeId);
		if (CollectionUtils.isEmpty(goodsProps)) {
			res.setData(null);
			res.setMsg("暂无店铺商品属性");
			return res;
		}

		Map<Long, GoodsPractVO> propMap = new HashMap<Long, GoodsPractVO>();

		List<GoodsPractVO> propList = new ArrayList<GoodsPractVO>();

		// 将店铺菜品属性数据封装
		for (GoodsPropsExtend props : goodsProps) {
			if (new Integer(5).equals(props.getPropCategoryTypeId())) {
				GoodsPractVO goodsPractVO = propMap.get(props.getPropCategoryId());
				if (goodsPractVO == null) {
					goodsPractVO = new GoodsPractVO();
					goodsPractVO.setPropCategoryId(props.getPropCategoryId());
					goodsPractVO.setPropCategoryName(props.getPropCategoryName());
					if (Utils.isEmpty(props.getIsMustOption())){
                        goodsPractVO.setIsMustOption(0);
                    }else {
                        goodsPractVO.setIsMustOption(props.getIsMustOption());
                    }
					goodsPractVO
							.setPropIsRadio(props.getPropIsRadio() == null ? new Integer(0) : props.getPropIsRadio());
					propMap.put(goodsPractVO.getPropCategoryId(), goodsPractVO);
					propList.add(goodsPractVO);
				}
				GoodsPropsVO goodsPropsVO = new GoodsPropsVO();
				goodsPropsVO.setPropCategoryId(props.getPropCategoryId());
				goodsPropsVO.setPropCategoryName(props.getPropCategoryName());
				goodsPropsVO.setPropCategoryTypeId(props.getPropCategoryTypeId());
				goodsPropsVO.setPropId(props.getPropId());
				goodsPropsVO.setPropName(props.getPropName());
				goodsPropsVO.setPropValue(props.getPropValue());
				goodsPractVO.getGoodsProps().add(goodsPropsVO);
			}
		}
		res.setData(propList);
		return res;
	}

	@Override
	public CoreResponse<List<GoodsVO>> getGoodsInfoByGoodsName(Integer shopperId, Integer storeId, String shopId,
			Long machineId, String goodsName) {
		CoreResponse<List<GoodsVO>> res = new CoreResponse<List<GoodsVO>>();
		// 查询店铺所有配置
		Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);

		// map转成对象
		ShopperConfigExtend shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);

		// 查询是否先付后吃模式
		Integer isFirstPay = shopperConfigExt.getFirstPayMent();

		// 查询是否开启分时段售卖
		Integer openSaleInteral = shopperConfigExt.getOpenSaleInteral();

		// 商家自定义本周最火是否启用手动优先
		Integer hotLevel = shopperConfigExt.getHotLevel();
		// 商家自定义本周最火显示数量
		Integer hotQuantity = shopperConfigExt.getHotQuantity();
		if(hotQuantity==null || new Integer(0).equals(hotQuantity)){
			hotQuantity = Integer.valueOf(hotGoodNum);
		}
		String startDate = DateUtils.getTodayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		
		GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
		goodsExtendParam.setShopperId(shopperId);
		goodsExtendParam.setStoreId(storeId);
		if (machineId != null) {
			goodsExtendParam.setMachineId(machineId);
		}
		goodsExtendParam.setIsFirstPay(isFirstPay);
		goodsExtendParam.setGoodsName(goodsName);
		goodsExtendParam.setStartDate(startDate);
		goodsExtendParam.setEndDate(endDate);
		goodsExtendParam.setNowDate(nowDate);
		// 获取商品信息
		List<CategoryGoods> categoryGoods = shopperGoodsServiceApi.searchGoodsByGoodsName(goodsExtendParam);

		if (CollectionUtils.isEmpty(categoryGoods)) {
			return null;
		}

		// 本周热销
		List<HotGoodsWeek> hotList = new ArrayList<HotGoodsWeek>();
		// 查询是否存在本周最火商品
		hotList = shopperGoodsServiceApi.getOldHotGoodsWeek(storeId, DateUtils.getTodayStartTime(),
				DateUtils.getTodayEndTime());
		// 执行存储过程插入本周最火商品
		if (CollectionUtils.isEmpty(hotList)) {
			shopperGoodsServiceApi.updateHotByCallAble(storeId, shopperId, 
					DateUtils.getDateChangeString(DateUtils.sevenDaysAgoTime()), DateUtils.getTodayStartTime());
		}
		//获取本周最火商品
		List<HotGoodsWeek> hotGoodsWeekList = shopperGoodsServiceApi.getHotWeekGoods(storeId, hotLevel, hotQuantity);

		// 今日特惠商品
		List<DiscountInfo> discountInfoList = new ArrayList<DiscountInfo>();
		if (shopId != null) {
		}

		List<GoodsVO> goodsList = new ArrayList<GoodsVO>();
		List<DaypartingGoods> daypartingGoods = null;
		// 查询分时段售卖商品
		if (new Integer(1).equals(openSaleInteral)) {
			int weekNum = DateUtils.getDayofweek();
			daypartingGoods = shopperGoodsServiceApi.getDaypartingGoods(storeId, weekNum, nowDate);
			if (CollectionUtils.isEmpty(daypartingGoods)) {
				for (CategoryGoods goods : categoryGoods) {
					for (DaypartingGoods dayGoods : daypartingGoods) {
						if (goods.getGoodsId().equals(dayGoods.getGoodsId())
								&& goods.getSizeId().equals(dayGoods.getSizeid())) {
							// GoodsVO goodsVO = conversionGoodsVO(goods);
							// int count = 1;
							// if (!CollectionUtils.isEmpty(hotGoodsWeekList) &&
							// count <= 10) {
							// for (HotGoodsWeek hotGoods : hotGoodsWeekList) {
							// if
							// (hotGoods.getGoodsId().equals(goods.getGoodsId())
							// &&
							// hotGoods.getSizeId().equals(goods.getSizeId())) {
							// goodsVO.setSalesVolume(hotGoods.getSalesVolume());
							// count++;
							// break;
							// }
							// }
							// }
							// if(!CollectionUtils.isEmpty(discountInfoList)){
							// for(DiscountInfo discountInfo:discountInfoList){
							// if(discountInfo.getGoodsId().equals(goods.getGoodsId())){
							// goodsVO.setDiscountInfo(discountInfo);
							// break;
							// }
							// }
							// }
							installGoodsList(hotGoodsWeekList, discountInfoList, goods, goodsList);
						}
					}
				}
			}
		} else {
			for (CategoryGoods goods : categoryGoods) {
				// GoodsVO goodsVO = conversionGoodsVO(goods);
				// int count = 1;
				// if (!CollectionUtils.isEmpty(hotGoodsWeekList) && count <=
				// 10) {
				// for (HotGoodsWeek hotGoods : hotGoodsWeekList) {
				// if (hotGoods.getGoodsId().equals(goods.getGoodsId())
				// && hotGoods.getSizeId().equals(goods.getSizeId())) {
				// goodsVO.setSalesVolume(hotGoods.getSalesVolume());
				// count++;
				// break;
				// }
				// }
				// }
				// if(!CollectionUtils.isEmpty(discountInfoList)){
				// for(DiscountInfo discountInfo:discountInfoList){
				// if(discountInfo.getGoodsId().equals(goods.getGoodsId())){
				// goodsVO.setDiscountInfo(discountInfo);
				// break;
				// }
				// }
				// }
				// goodsList.add(goodsVO);
				installGoodsList(hotGoodsWeekList, discountInfoList, goods, goodsList);
			}
		}
		res.setData(goodsList);
		res.setMsg("获取商品信息成功");
		return res;
	}

	private void installGoodsList(List<HotGoodsWeek> hotGoodsWeekList, List<DiscountInfo> discountInfoList,
			CategoryGoods goods, List<GoodsVO> goodsList) {
		GoodsVO goodsVO = conversionGoodsVO(goods);
		int count = 1;
		if (!CollectionUtils.isEmpty(hotGoodsWeekList) && count <= 10) {
			for (HotGoodsWeek hotGoods : hotGoodsWeekList) {
				if (hotGoods.getGoodsId().equals(goods.getGoodsId())
						&& hotGoods.getSizeId().equals(goods.getSizeId())) {
					goodsVO.setSalesVolume(hotGoods.getSalesVolume());
					count++;
					break;
				}
			}
		}
		if (!CollectionUtils.isEmpty(discountInfoList)) {
			for (DiscountInfo discountInfo : discountInfoList) {
				if (discountInfo.getGoodsId().equals(goods.getGoodsId())) {
					DiscountInfoVO discountInfoVO = null;
					if (discountInfo != null) {
						discountInfoVO = new DiscountInfoVO();
						BeanUtils.copyProperties(discountInfo, discountInfoVO);
					}
					goodsVO.setDiscountInfo(discountInfoVO);
					break;
				}
			}
		}
		goodsList.add(goodsVO);
	}

	@Override
	public CoreResponse<List<CopyGoodsVO>> getCopyPageInfo(Integer storeId, String tableUid) {

		CoreResponse<List<CopyGoodsVO>> res = new CoreResponse<List<CopyGoodsVO>>();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		List<CopyGoods> copyGoods = waimaiServiceApi.getCopyGoods(storeId, tableUid, startDate, endDate);
		if (CollectionUtils.isEmpty(copyGoods)) {
			res.setData(null);
			res.setMsg("暂无其他桌台信息");
			return res;
		}
		Map<String, CopyGoodsVO> tableMaps = new HashMap<String, CopyGoodsVO>();
		List<CopyGoodsVO> copyGoodsList = new ArrayList<CopyGoodsVO>();
		for (CopyGoods goods : copyGoods) {
			CopyGoodsVO tableMap = tableMaps.get(goods.getTableNum());
			if (tableMap == null) {
				tableMap = new CopyGoodsVO();
				tableMaps.put(goods.getTableNum(), tableMap);
				copyGoodsList.add(tableMap);
				tableMap.setTableName(goods.getTableNum());
			}
			GoodsAndSizeVO goodsAndSize = new GoodsAndSizeVO();
			goodsAndSize.setGoodsId(goods.getGoodsId());
			goodsAndSize.setSizeId(goods.getSizeId());
			tableMap.getGoodsAndSize().add(goodsAndSize);
		}
		res.setData(copyGoodsList);
		return res;
	}

	@Override
	public List<GroupPackageSuitVO> getSingleGroupPackageGoods(Integer storeId, Integer shopperId, Integer goodsId) {
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		List<CombinationPackage> groupPackage = shopperGoodsServiceApi.getCombinationPackage(shopperId, storeId,
				startDate, endDate, nowDate, goodsId);
		if (Utils.isEmpty(groupPackage)) {
			return null;
		}
		// 定义分组下商品数据
		Map<String, GroupPackageSuitVO> groupPackageSuit = new HashMap<String, GroupPackageSuitVO>();
		List<GroupPackageSuitVO> groupPackageList = new ArrayList<GroupPackageSuitVO>();
		for (CombinationPackage packages : groupPackage) {
			// 判断是否存在套餐的分组数据
			GroupPackageSuitVO groupPackageSuitVO = groupPackageSuit
					.get(packages.getPackageId() + "_" + packages.getSuitGroupId());
			if (groupPackageSuitVO == null) {
				groupPackageSuitVO = new GroupPackageSuitVO();
				groupPackageSuitVO.setSuitId(packages.getSuitGroupId());
				groupPackageSuitVO.setSuitName(packages.getSuitGroupName());
				groupPackageSuitVO.setSuitStartNumber(packages.getSuitStartNumber());
				groupPackageSuitVO.setSuitEndNumber(packages.getSuitEndNumber());
				groupPackageSuitVO.setSuitState(packages.getSuitState());
				groupPackageSuitVO.setSuitSort(packages.getSuitSort());
				groupPackageSuit.put(packages.getPackageId() + "_" + packages.getSuitGroupId(), groupPackageSuitVO);
				groupPackageList.add(groupPackageSuitVO);
			}
			GroupPackageGoodsVO groupPackageGoods = new GroupPackageGoodsVO();
			BeanUtils.copyProperties(packages, groupPackageGoods);
			groupPackageSuitVO.getGroupGoods().add(groupPackageGoods);
		}

		return groupPackageList;
	}

	@Override
	public Map<Integer, GoodsPropsCVO> getSingleGoodsPropInfo(Integer goodsId, Integer storeId, Integer shopperId) {
        //获取redis店铺配置信息
        Object config = redisService.getObj(storeId + "_shopperConfig");
        ShopperConfigExtend shopperConfigExt = null;
        if (config == null) {
            // 查询店铺所有配置
            Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
            // map转成对象
            shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
        } else {
            shopperConfigExt = (ShopperConfigExtend) config;
        }

        //查询是否开启商品默认规格显示
       /* Integer isGoodsSizeDefault=shopperConfigExt.getIsGoodsSizeDefaultShow();*/
        List<CategoryGoodsDetail> goodsDetailList=null;
        //logger.info("===============默认规格商品详情");
        /*if (isGoodsSizeDefault!=null && isGoodsSizeDefault==1){
            //查询商品详情
            goodsDetailList= shopperGoodsServiceApi.getGoodsDetail(storeId, goodsId);
        }*/
		List<GoodsPropsExtend> goodsProps = shopperGoodsServiceApi.getGoodsBindPropsList(goodsId, shopperId, storeId);
		List<GoodsPropsExtend>  goodsCookings = shopperGoodsServiceApi.getGoodsCookingsList(goodsId, shopperId);
		if (CollectionUtils.isEmpty(goodsProps) && CollectionUtils.isEmpty(goodsCookings)) {
			return null;
		}

		// 组装商品属性数据
		Map<Integer, GoodsPropsCVO> goodsPropsMap = installGoodsProps(goodsProps,goodsCookings);
		return goodsPropsMap;
	}

	public List<OrdinaryPackageVO> getSingleNormalPackageGoods(Integer shopperId, Integer storeId, Integer goodsId) {
		// 获取店铺单个商品的普通套餐信息
		List<NormalPackage> normalPackage = shopperGoodsServiceApi.getNormalPackage(shopperId, storeId, goodsId);
		if (CollectionUtils.isEmpty(normalPackage)) {
			return null;
		}
		// 获取所有商品属性信息
		List<GoodsPropsExtend> goodsProps = shopperGoodsServiceApi.getAllGoodsBindPropsList(shopperId, storeId);
		// 获取所有商品加价信息
		List<GoodsPropsExtend> goodsCookings = shopperGoodsServiceApi.getAllGoodsCookingsList(shopperId);
		Map<Integer, GoodsPropsCVO> goodsPropsMap = null;
	
		// 组装商品属性数据
		goodsPropsMap = installGoodsProps(goodsProps,goodsCookings);
		List<OrdinaryPackageVO> ordinaryPackage = new ArrayList<OrdinaryPackageVO>();
		for (NormalPackage packages : normalPackage) {
			//如果套餐子商品数量大于2且存在属性是，传给前端时需要拆分个单个
			if (packages.getGoodsNum() >= 2 && goodsPropsMap != null
					&& goodsPropsMap.get(packages.getGoodsId()) != null) {
				for(int i=0;i<packages.getGoodsNum();i++){
					OrdinaryPackageVO ordinaryPackageVO = new OrdinaryPackageVO();
					ordinaryPackageVO.setGoodsId(packages.getGoodsId());
					ordinaryPackageVO.setGoodsName(packages.getGoodsName());
					ordinaryPackageVO.setGoodsNum(1d);
					ordinaryPackageVO.setSizeId(packages.getSizeId());
					ordinaryPackageVO.setSizeTypeName(packages.getSizeTypeName());
					ordinaryPackageVO.setCategoryId(packages.getCategoryId());
					ordinaryPackageVO.setCategoryName(packages.getCategoryName());
					ordinaryPackageVO.setDescription(packages.getDescription());
					ordinaryPackageVO.setImagePath(packages.getImagePath());
					ordinaryPackageVO.setIsPackage(packages.getIsPackage());
					ordinaryPackageVO.setIsWeight(packages.getIsWeight());
					ordinaryPackageVO.setMinAddUnit(packages.getMinAddUnit() == null ? 0 : packages.getMinAddUnit());
					ordinaryPackageVO.setMinSell(packages.getMinSell() == null ? 0 : packages.getMinSell());
					ordinaryPackageVO.setPrice(packages.getPrice());
					ordinaryPackageVO.setSizeCount(packages.getSizeCount());
					ordinaryPackageVO.setSpicyName(packages.getSpicyName());
					ordinaryPackageVO.setSpicyValue(packages.getSpicyValue());
					ordinaryPackageVO.setSpicyImagePath(packages.getSpicyImagePath());
					if (goodsPropsMap != null && goodsPropsMap.get(packages.getGoodsId()) != null) {
						ordinaryPackageVO.setGoodsProps(goodsPropsMap.get(packages.getGoodsId()));
					}
					ordinaryPackage.add(ordinaryPackageVO);
				}
			}else{
				OrdinaryPackageVO ordinaryPackageVO = new OrdinaryPackageVO();
				ordinaryPackageVO.setGoodsId(packages.getGoodsId());
				ordinaryPackageVO.setGoodsName(packages.getGoodsName());
				ordinaryPackageVO.setGoodsNum(packages.getGoodsNum());
				ordinaryPackageVO.setSizeId(packages.getSizeId());
				ordinaryPackageVO.setSizeTypeName(packages.getSizeTypeName());
				ordinaryPackageVO.setCategoryId(packages.getCategoryId());
				ordinaryPackageVO.setCategoryName(packages.getCategoryName());
				ordinaryPackageVO.setDescription(packages.getDescription());
				ordinaryPackageVO.setImagePath(packages.getImagePath());
				ordinaryPackageVO.setIsPackage(packages.getIsPackage());
				ordinaryPackageVO.setIsWeight(packages.getIsWeight());
				ordinaryPackageVO.setMinAddUnit(packages.getMinAddUnit() == null ? 0 : packages.getMinAddUnit());
				ordinaryPackageVO.setMinSell(packages.getMinSell() == null ? 0 : packages.getMinSell());
				ordinaryPackageVO.setPrice(packages.getPrice());
				ordinaryPackageVO.setSizeCount(packages.getSizeCount());
				ordinaryPackageVO.setSpicyName(packages.getSpicyName());
				ordinaryPackageVO.setSpicyValue(packages.getSpicyValue());
				ordinaryPackageVO.setSpicyImagePath(packages.getSpicyImagePath());
				if (goodsPropsMap != null && goodsPropsMap.get(packages.getGoodsId()) != null) {
					ordinaryPackageVO.setGoodsProps(goodsPropsMap.get(packages.getGoodsId()));
				}
				ordinaryPackage.add(ordinaryPackageVO);
			}
		}
		return ordinaryPackage;
	}

	@Override
	public List<GroupPackageSuitVO> getSingleGroupPackageGoodsByProp(Integer storeId, Integer shopperId,
			Integer goodsId) {
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		List<CombinationPackage> groupPackage = shopperGoodsServiceApi.getCombinationPackage(shopperId, storeId,
				startDate, endDate, nowDate, goodsId);
		if (Utils.isEmpty(groupPackage)) {
			return null;
		}		
		// 获取所有商品属性信息
		List<GoodsPropsExtend> goodsProps = shopperGoodsServiceApi.getAllGoodsBindPropsList(shopperId, storeId);
		// 获取所有商品加价信息
		List<GoodsPropsExtend> goodsCookings = shopperGoodsServiceApi.getAllGoodsCookingsList(shopperId);
		Map<Integer, GoodsPropsCVO> goodsPropsMap = null;
		// 组装商品属性数据
		goodsPropsMap = installGoodsProps(goodsProps,goodsCookings);
		// 定义分组下商品数据
		Map<String, GroupPackageSuitVO> groupPackageSuit = new HashMap<String, GroupPackageSuitVO>();
		List<GroupPackageSuitVO> groupPackageList = new ArrayList<GroupPackageSuitVO>();

		for (CombinationPackage packages : groupPackage) {
			// 判断是否存在套餐的分组数据
			GroupPackageSuitVO groupPackageSuitVO = groupPackageSuit
					.get(packages.getPackageId() + "_" + packages.getSuitGroupId());
			if (groupPackageSuitVO == null) {
				groupPackageSuitVO = new GroupPackageSuitVO();
				groupPackageSuitVO.setSuitId(packages.getSuitGroupId());
				groupPackageSuitVO.setSuitName(packages.getSuitGroupName());
				groupPackageSuitVO.setSuitStartNumber(packages.getSuitStartNumber());
				groupPackageSuitVO.setSuitEndNumber(packages.getSuitEndNumber());
				groupPackageSuitVO.setSuitState(packages.getSuitState());
				groupPackageSuitVO.setSuitSort(packages.getSuitSort());
				groupPackageSuit.put(packages.getPackageId() + "_" + packages.getSuitGroupId(), groupPackageSuitVO);
				groupPackageList.add(groupPackageSuitVO);
			}
			GroupPackageGoodsVO groupPackageGoods = new GroupPackageGoodsVO();
			BeanUtils.copyProperties(packages, groupPackageGoods);
			//商品加价
			if(groupPackageGoods.getPlusPrice()==null){
				groupPackageGoods.setPlusPrice(0d);
			}
			//组合套餐内商品默认不可复选
			if(groupPackageGoods.getIsCheck()==null){
				groupPackageGoods.setIsCheck(0);
			}
			//组合套餐内商品默认不必选
			if(groupPackageGoods.getIsRequre()==null){
				groupPackageGoods.setIsRequre(0);
			}
			if (goodsPropsMap != null && goodsPropsMap.get(packages.getGoodsId()) != null) {
				groupPackageGoods.setGoodsProps(goodsPropsMap.get(packages.getGoodsId()));
			}
			groupPackageSuitVO.getGroupGoods().add(groupPackageGoods);
		}
		
		return groupPackageList;

	}

	@Override
	public CoreResponse<List<KoubeiRecommendGoodsVO>> getKoubeiRecommendGoodsList(
			KoubeiRecomEntryVO koubeiRecomEntry) {
		CoreResponse<List<KoubeiRecommendGoodsVO>> res = new CoreResponse<List<KoubeiRecommendGoodsVO>>();
		
		// 调用口碑接口基本参数
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayServiceEnvConstants.ALIPAY_GATEWAY.getValue(),
				SWEEP_APP_ID, AlipayServiceEnvConstants.PRIVATE_KEY.getValue(), "json",
				AlipayServiceEnvConstants.CHARSET.getValue(), AlipayServiceEnvConstants.ALIPAY_PUBLIC_KEY.getValue());
		
		KoubeiCateringDishRecommendQueryRequest koubeiRequest = new KoubeiCateringDishRecommendQueryRequest();
		
		JSONObject json = new JSONObject();
		
		json.fluentPut("merchent_pid", koubeiRecomEntry.getMerchantPid())
				.fluentPut("shop_id", koubeiRecomEntry.getShopId()).fluentPut("user_id", koubeiRecomEntry.getBuyerId());
		if(!StringUtils.isEmpty(koubeiRecomEntry.getType())){
			json.fluentPut("type", koubeiRecomEntry.getType());
		}
		
		if((Constants.KoubeiDishType.ASSOCIATION_RECOMAND.getValue()).equals(koubeiRecomEntry.getType())){
			json.fluentPut("dish_list",koubeiRecomEntry.getDishList());
		}
		koubeiRequest.setBizContent(json.toJSONString());
		// 获取口碑推荐菜品
		KoubeiCateringDishRecommendQueryResponse response = null;
		try {
			response = alipayClient.execute(koubeiRequest);
		} catch (AlipayApiException e1) {
			e1.printStackTrace();
		}
		if (response == null || !response.isSuccess()) {
			res.setSubMsg("获取口碑推荐菜品失败");
			res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setData(null);
			return res;
		}
		// TODO 暂时写死
		//13数据
//		int[] arr = new int[] { 448995, 70780226, 453938, 453974, 453975, 449159, 449160,423671,436257,436396,436400,436401,437027,454219,454220,454715};
//		List<DishRecommend> list = new ArrayList<DishRecommend>();
//		for (int i : arr) {
//			DishRecommend d = new DishRecommend();
//			d.setBuyPosibility(Arith.div(i, 10000, 2) + "");
//			d.setDishId(i + "");
//			list.add(d);
//		}
		// TODO 上线时打开
		List<DishRecommend> list = response.getDishList();
		if (Utils.isEmpty(list)) { // 口碑返回推荐菜列表为空，直接返回为空
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setSubMsg("无口碑推荐菜品");
			res.setData(null);
			return res;
		}
		// 根据菜品ID过滤口碑返回菜品
		List<KoubeiRecommendGoodsVO> goodsVOList = new ArrayList<KoubeiRecommendGoodsVO>();
		KoubeiRecommendGoodsVO goodsVO = null;
		Map<Integer, DishRecommend> map = new HashMap<Integer, DishRecommend>();
		for (DishRecommend dish : list) {
			if (!Utils.isEmpty(dish.getDishId())) {
				DishRecommend dishRecommend = map.get(Integer.valueOf(dish.getDishId()));
				if (dishRecommend == null) {
					goodsVO = new KoubeiRecommendGoodsVO();
					map.put(Integer.valueOf(dish.getDishId()), dish);
					goodsVO.setGoodsId(Integer.valueOf(dish.getDishId()));
					goodsVO.setBuyPosibility(Double.valueOf(dish.getBuyPosibility()));
					goodsVOList.add(goodsVO);
				}
			}
		}
		if (Utils.isEmpty(goodsVOList)) {
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setSubMsg("无口碑推荐菜品");
			res.setData(null);
			return res;
		}
		// 根据菜品分数对菜品进行从高到低排序
		goodsVOList = sort(goodsVOList);
		// 获取排序后最多100个菜品的id
		List<Integer> goodsIds = new ArrayList<Integer>();
		for (int i = 0; i < goodsVOList.size() && i < 100; i++) {
			goodsIds.add(goodsVOList.get(i).getGoodsId());
		}
		if(CollectionUtils.isEmpty(goodsIds)){
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setMsg("无口碑推荐菜品");
			res.setData(null);
			return res;
		}
		//口碑推荐菜配类型为DESIGN_FOR_YOU（为你定制）不需要过滤购物车商品
		if (!(Constants.KoubeiDishType.DESIGN_FOR_YOU.getValue()).equals(koubeiRecomEntry.getType())) {
			String startDate = DateUtils.getYesterdayStartTime();
			String endDate = DateUtils.getTodayEndTime();
			List<GoodsCartAndDetail> goodsList = null;
			// 获取购物车商品信息
			if (!StringUtils.isEmpty(koubeiRecomEntry.getTableName())) {
				// 根据桌台查询
				goodsList = goodsCartServiceApi.getGoodsCartByTableNo(koubeiRecomEntry.getStoreId(), koubeiRecomEntry.getTableName(), startDate, endDate,koubeiRecomEntry.getClientOrderMode());
			} else {
				// 根据顾客Id查询
				goodsList = goodsCartServiceApi.getGoodsCartByBuyerId(koubeiRecomEntry.getStoreId(), koubeiRecomEntry.getBuyerId(), startDate, endDate,koubeiRecomEntry.getClientOrderMode());
			}
			//购物车不为空时，要去除购物车里存在的推荐菜
			if(!CollectionUtils.isEmpty(goodsList)){
				for(GoodsCartAndDetail goodsCart:goodsList){
					if(goodsIds.contains(goodsCart.getGoodsId()) || new Integer(2).equals(goodsCart.getIsPackage())){
						goodsIds.remove(goodsCart.getGoodsId());
					}
				}
			}
		}
		
		List<KoubeiRecommendGoodsVO> koubeiGoodsList = null;
		// 根据口碑返回的菜品Id去查询相对应的菜品规格sizeId（多种规格默认只获取任意一个）
		if(!CollectionUtils.isEmpty(goodsIds)){
			List<Size> sizeInfo = shopperGoodsServiceApi.getSizeInfoByGoodsId(goodsIds);
			if (!CollectionUtils.isEmpty(sizeInfo)) {
				koubeiGoodsList = new ArrayList<KoubeiRecommendGoodsVO>();
				for (Size size : sizeInfo) {
					KoubeiRecommendGoodsVO KoubeiGoodsVO = new KoubeiRecommendGoodsVO();
					KoubeiGoodsVO.setGoodsId(size.getGoodsId());
					KoubeiGoodsVO.setSizeId(size.getId());
					koubeiGoodsList.add(KoubeiGoodsVO);
				}
			}
		}
		if(CollectionUtils.isEmpty(koubeiGoodsList)){
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setSubMsg("无口碑推荐菜");
			return res;
		}
		
		res.setSubMsg("获取口碑推荐菜品成功");
		res.setStatusInfo(StatusInfo.SUCCESS);
		res.setData(koubeiGoodsList);
		return res;
	}

	@Override
	public CoreResponse<Map<String,Integer>> getNeedGoodsAddCart(NeedGoodsAddCart needGoodsAddCart) {
		
		CoreResponse<Map<String,Integer>> res = new CoreResponse<Map<String,Integer>>();
		Map<String,Integer> needMap = new HashMap<String,Integer>();
		//新增的必选商品
		List<GoodsCartAndDetail> goodsCartList = new ArrayList<GoodsCartAndDetail>();
		//已删除的可修改必选菜
		List<GoodsCart> deletedNeedList = new ArrayList<GoodsCart>();
		//购物车里面历史商品
		List<GoodsCartAndDetail> hostoryList = new ArrayList<GoodsCartAndDetail>();
		
		//默认存在必选菜
		needMap.put("mustGoods", 1);
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		DiningArea diningArea = null;
		
		//获取桌台信息
		if(needGoodsAddCart.getTableInfoId()!=null){
			diningArea = shopperInfoServiceApi.getDiningAreaById(needGoodsAddCart.getTableInfoId());			
		}
		
		if (diningArea!=null && StringUtils.isNotEmpty(diningArea.getName())) {
			hostoryList = goodsCartServiceApi.getGoodsCartByTableNo(needGoodsAddCart.getStoreId(), diningArea.getName(), startDate, endDate,needGoodsAddCart.getClientOrderMode());
			deletedNeedList = goodsCartServiceApi.getDeletedNeedGoodsCartByTableNo(needGoodsAddCart.getStoreId(), diningArea.getName(),startDate, endDate);
		}else{
			hostoryList = goodsCartServiceApi.getGoodsCartByBuyerId(needGoodsAddCart.getStoreId(), needGoodsAddCart.getBuyerId(),startDate, endDate,needGoodsAddCart.getClientOrderMode());
			deletedNeedList = goodsCartServiceApi.getDeletedNeedGoodsCartByBuyerId(needGoodsAddCart.getStoreId(), needGoodsAddCart.getBuyerId(),startDate, endDate);
		}
		
		//购物车为空且已删除可修改必选菜不为空则清空所有的已删除可修改必选菜记录
		if(CollectionUtils.isEmpty(hostoryList) && !CollectionUtils.isEmpty(deletedNeedList)){
			if (diningArea!=null && StringUtils.isNotEmpty(diningArea.getName())) {
				goodsCartServiceApi.removeDeletedNeedGoodsCartByTableNo(needGoodsAddCart.getStoreId(), diningArea.getName(), startDate, endDate);
			}else{
				goodsCartServiceApi.removeDeletedNeedGoodsCartByBuyerId(needGoodsAddCart.getStoreId(), needGoodsAddCart.getBuyerId(),startDate, endDate);
			}
			deletedNeedList = null;
		}
		
		//删除购物车必选菜品，重新添加
		GoodsCartExtend goodsCartExtend = new GoodsCartExtend();
		goodsCartExtend.setStoreId(needGoodsAddCart.getStoreId());
		goodsCartExtend.setStartDate(startDate);
		goodsCartExtend.setEndDate(endDate);
		goodsCartExtend.setMustOrder(1);
		if (diningArea!=null && StringUtils.isNotEmpty(diningArea.getName())) {
			goodsCartExtend.setBuyerId("system");
			goodsCartExtend.setTableNo(diningArea.getName());
		}else{
			goodsCartExtend.setBuyerId("system_"+needGoodsAddCart.getBuyerId());
		}
		
		//获取必选菜信息查询条件
		GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
		goodsExtendParam.setStoreId(needGoodsAddCart.getStoreId());
		goodsExtendParam.setShopperId(needGoodsAddCart.getShopperId());
		if(diningArea!=null){
			goodsExtendParam.setTableUid(diningArea.getUid());
		}
		goodsExtendParam.setStartDate(startDate);
		goodsExtendParam.setEndDate(endDate);
		goodsExtendParam.setNowDate(nowDate);
		//获取必选菜商品信息
		List<CategoryGoods> needGoods = shopperGoodsServiceApi.getNeedGoodsInfoList(goodsExtendParam);
		if(CollectionUtils.isEmpty(needGoods)){
			//默认没有必选菜
			needMap.put("mustGoods", 0);
			//删除购物车存在的必选菜
			goodsCartServiceApi.updateGoodsCartForMustGoods(goodsCartExtend,null);	
			res.setSubMsg("本店铺暂未配置必选菜商品");
			res.setData(needMap);
			return res;
		}
		//获取进行中扫码下单查询条件
		WaimaiParam param = new WaimaiParam();
		param.setStoreId(needGoodsAddCart.getStoreId());
		param.setPayStatus(0);
		param.setStartDate(startDate);
		param.setEndDate(endDate);
		Waimai waimai = null;
		
		//获取店铺配置信息
		Object config = redisService.getObj(needGoodsAddCart.getStoreId()+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if(config!=null){
			shopperConfigExt = (ShopperConfigExtend)config;
		}else{
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(needGoodsAddCart.getStoreId());
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		}
		//获取进行中订单信息(只考虑扫码下单是否存在订单存在订单则不能再将必选菜写入购物车，在线订单每次调都可以将必选菜写入购物车)
		if(diningArea!=null && !StringUtils.isEmpty(diningArea.getName())){
			param.setTableNum(diningArea.getName());
			if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getKoubeiDinner())) {
				// 口碑正餐后付订单
				param.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
			} else {
				// 扫码下单订单
				param.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
			}
			param.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
			param.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
			param.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			param.getStatuses().add(Constants.orderStatus.STATUS_THREE.getValue());
			waimai = waimaiServiceApi.getWaimaiByTableNum(param);
		}
		if (waimai == null || (waimai != null && new Integer(-1).equals(waimai.getOrderStatus())
				&& (DateUtils.currentTime().getTime() - waimai.getCreateTime().getTime() > 1000 * 60 * 3))) {
			if(!CollectionUtils.isEmpty(needGoods)){
				//判断登录模式
				if(!new Integer(2).equals(needGoodsAddCart.getAuthMode())){
					needGoodsAddCart.setAuthMode(1);
				}
				//获取顾客信息
				ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(needGoodsAddCart.getBuyerId(), needGoodsAddCart.getAuthMode());
				if(thirdUserInfo==null){
					res.setStatusInfo(StatusInfo.ERROR_40001);
					res.setSubMsg("用户参数有误");
					return res;
				}
				String buyerId = thirdUserInfo.getThirdUserId();
				// 用户昵称
				String nickName = StringUtils.isEmpty(thirdUserInfo.getNickName()) ? "吃货" : thirdUserInfo.getNickName();
				// 用户头像
				String avatar = thirdUserInfo.getAvatar();
				int i = 0;
				for (CategoryGoods goods : needGoods) {
					// 过滤起卖数、叠加数、组合套餐商品；如果桌台不存在且必点菜只绑定部分桌台则不将必选菜加入购物车
					if (new Integer(2).equals(goods.getIsPackage()) || 
							(new Integer(1).equals(goods.getRequiredStatus())
									  && (diningArea==null || StringUtils.isEmpty(diningArea.getUid())))) {
						i++;
						continue;
					} else {
						//必选菜默认起卖份数
						Integer buyCount = (goods.getDefaultAdd()==null || goods.getDefaultAdd()==0)?1:goods.getDefaultAdd();
						//取传参人数
						Integer peopleNumber = (needGoodsAddCart.getPeopleNumber() == null || needGoodsAddCart.getPeopleNumber() ==0)?1:needGoodsAddCart.getPeopleNumber();
						//取redis人数 
						if(needGoodsAddCart.getPeopleNumber() == null || needGoodsAddCart.getPeopleNumber() ==0){
							Object number =null;
							if(needGoodsAddCart.getTableInfoId()!=null){
								number = redisService.getObj(needGoodsAddCart.getStoreId()+"_"+needGoodsAddCart.getTableInfoId());	
							}else{
								number = redisService.getObj(needGoodsAddCart.getStoreId()+"_"+needGoodsAddCart.getBuyerId());						
							}
							peopleNumber = StringUtils.isEmpty(String.valueOf(number))?0:Integer.valueOf(String.valueOf(number));
						}
						if(peopleNumber==null || peopleNumber==0){
							peopleNumber = 1;
						}
						//必选菜是否和就餐人数关联
						if(new Integer(1).equals(goods.getIsRelatedPerson())){
							buyCount = buyCount * peopleNumber;
						}
						GoodsCartAndDetail goodsCart = new GoodsCartAndDetail();
						goodsCart.setBuyCount((double)buyCount);
						//默认图片
						if(Utils.isEmpty(goods.getImagePath())){
							goodsCart.setGoodsImg("res/imggoodspic.png");
						}else{
							goodsCart.setGoodsImg(goods.getImagePath());
						}
						//桌台是否存在
						if(diningArea!=null && !Utils.isEmpty(diningArea.getName())){
							goodsCart.setBuyerId("system");
							goodsCart.setTableNo(diningArea.getName());
						}else{
							goodsCart.setTableNo(null);
							goodsCart.setBuyerId("system_"+buyerId);
						}
						goodsCart.setBuyPrice(goods.getPrice());
						goodsCart.setCategoryId(goods.getCategoryId());
						goodsCart.setCategoryName(goods.getCategoryName());
						goodsCart.setDetails(null);
						
						goodsCart.setDiscountItemId(null);
						goodsCart.setDiscountRate(null);
						goodsCart.setIsSingleDiscount(null);
						goodsCart.setItemType(null);
						
						goodsCart.setCreateTime(new Date());
						goodsCart.setGoodsDesc("");
						goodsCart.setIsNotshowSize(goods.getSizeCount()>=2?0:1);//0显示规格  1不显示规格
						goodsCart.setMinAddUnit(0);
						goodsCart.setMinSell(0);
						goodsCart.setGoodsId(goods.getGoodsId());
						goodsCart.setGoodsName(goods.getGoodsName());
						goodsCart.setIsPackage(goods.getIsPackage());
						goodsCart.setIsWeight(0);
						goodsCart.setOriginalPrice(goods.getPrice());
						goodsCart.setShopperId(needGoodsAddCart.getStoreId());
						goodsCart.setSizeType(goods.getSizeType());
						goodsCart.setSizeId(goods.getSizeId());
						goodsCart.setMustOrderUpdate(goods.getIsModified());
						goodsCart.setAvatarPath(avatar);
						goodsCart.setBuyNick(nickName);
						
						goodsCart.setPropIds("");
						goodsCart.setPropPrice(null);
						goodsCart.setPropNames(null);
						goodsCart.setMustOrder(new Integer(1));
						goodsCartList.add(goodsCart);
					}
				}
				//是否存在必选菜加入购物车
				if(needGoods.size()==i){
					needMap.put("mustGoods",0);
				}
			}
			List<GoodsCartAndDetail> newGoodsCartList = new ArrayList<GoodsCartAndDetail>();
			newGoodsCartList.addAll(goodsCartList);
			//购物车如果有商品
			if(!CollectionUtils.isEmpty(hostoryList) && !CollectionUtils.isEmpty(deletedNeedList) && !CollectionUtils.isEmpty(goodsCartList)){
				for (GoodsCartAndDetail goodsCartAndDetail : goodsCartList) {
					//过滤购物车内已删除的必选菜
					for (GoodsCart dGoodsCart : deletedNeedList) {
						if((dGoodsCart.getGoodsId().equals(goodsCartAndDetail.getGoodsId())) && (dGoodsCart.getSizeId().equals(goodsCartAndDetail.getSizeId()))){
							newGoodsCartList.remove(goodsCartAndDetail);
						}
					}
				}
			}
			if(!CollectionUtils.isEmpty(newGoodsCartList)){
				//删除和新增必选菜
				goodsCartServiceApi.updateGoodsCartForMustGoods(goodsCartExtend,newGoodsCartList);
			}
		}
		res.setSubMsg("必选菜已加入购物车");
		res.setData(needMap);
		return res;
	}

	@Override
	public List<AlreadyGoods> getAlreadyGoods(Integer storeId,Long thirdUserInfoId) {
		List<AlreadyGoods> arealdyGoods = waimaiServiceApi.getAlreadyGoods(storeId,thirdUserInfoId,DateUtils.getDateChangeString(DateUtils.fifteenDaysAgoTime()));	
		 return arealdyGoods;
	}

	@Override
	public QrcodeGoodsVO getQrcodeGoodsInfo(Integer storeId, Integer goodsId, Long sizeId) {
		
		// 获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//获取redis店铺白名单配置信息
		Object shopperWhite = redisService.getObj(storeId+"_shopperWhite");
		// 查询是否先付后吃模式
		Integer isFirstPay = shopperConfigExt.getFirstPayMent();
		GoodsExtendParam goodsExtendParam = new GoodsExtendParam();
		// 售罄时间
		String dateStart = DateUtils.getTodayStartTime();
		String dateEnd = DateUtils.getTodayEndTime();
		String nowDate = DateUtils.getNowTime();
		goodsExtendParam.setStoreId(storeId);
		goodsExtendParam.setIsFirstPay(isFirstPay);
		goodsExtendParam.setStartDate(dateStart);
		goodsExtendParam.setEndDate(dateEnd);
		goodsExtendParam.setNowDate(nowDate);
		if(shopperWhite!=null){
			Map<String,Integer> whiteMap = (HashMap<String, Integer>)shopperWhite;
			if(whiteMap!=null){
				goodsExtendParam.setStoreCategory(whiteMap.get("storeCategory"));
			}
		}
		goodsExtendParam.setSizeId(sizeId);
		goodsExtendParam.setGoodsId(goodsId);
		//获取单个商品信息
		List<CategoryGoods> goodsList = shopperGoodsServiceApi.getGoodsInfoByGoodsId(goodsExtendParam);
		if(CollectionUtils.isEmpty(goodsList)){
			return null;
		}
		QrcodeGoodsVO goodsVO = new QrcodeGoodsVO();
		List<SizePriceVO> sizePriceList = new ArrayList<SizePriceVO>();
		boolean flag = true;
		double minPrice = 0d;
		double maxPrice = 0d;
		for (CategoryGoods goods : goodsList) {
			if (flag) {
				goodsVO.setCategoryId(goods.getCategoryId());
				goodsVO.setCategoryName(goods.getCategoryName());
				goodsVO.setDescription(goods.getDescription());
				goodsVO.setGoodsAddNum(goods.getMinAddUnit()==null?1:goods.getMinAddUnit());
				goodsVO.setGoodsSellNum(goods.getMinSell()==null?1:goods.getMinSell());
				goodsVO.setGoodsId(goods.getGoodsId());
				goodsVO.setGoodsName(goods.getGoodsName());
				goodsVO.setImagePath(goods.getImagePath());
				goodsVO.setIsPackage(goods.getIsPackage());
				goodsVO.setIsSellOut(goods.getIsSellOut());
				goodsVO.setIsWeight(goods.getIsWeight());
				goodsVO.setSizeCount(goods.getSizeCount());
				goodsVO.setIsProp(goods.getIsProp());
				// 获取店铺信息数据
				ShopperInfo shopper = shopperInfoServiceApi.getShopperInfo(storeId, nowDate);
				List<DiscountInfo> discountInfoList = new ArrayList<DiscountInfo>();
				DiscountInfoVO discountInfo = null;
				// 添加商品优惠新
				if (shopper != null && !StringUtils.isEmpty(shopper.getShopId())) {
					discountInfoList = shopperGoodsServiceApi.getDiscountGoods(shopper.getShopId(), goodsId, nowDate,
							DateUtils.getDayofweek());
					if (!CollectionUtils.isEmpty(discountInfoList) && discountInfoList.get(0) != null) {
						DiscountInfo Info = discountInfoList.get(0);
						discountInfo = new DiscountInfoVO();
						discountInfo.setDiscountInfo(Info.getDiscountInfo());
						discountInfo.setGoodsId(Info.getGoodsId());
						discountInfo.setIsSingleDiscount(Info.getIsSingleDiscount());
						discountInfo.setItemId(Info.getItemId());
						discountInfo.setItemType(Info.getItemType());
					}
				}
				goodsVO.setDiscountInfo(discountInfo);
				flag = false;
			}
			SizePriceVO sizePrice = new SizePriceVO(); 
			sizePrice.setPrice(goods.getPrice());
			sizePrice.setSizeId(goods.getSizeId());
			sizePrice.setSizeType(goods.getSizeType());
			sizePriceList.add(sizePrice);
		}
		//判断多规格商品最低价和最高价
		if(!CollectionUtils.isEmpty(sizePriceList)){
			minPrice = sizePriceList.get(0).getPrice();
			maxPrice = sizePriceList.get(0).getPrice();
			for(SizePriceVO price:sizePriceList){
				if(minPrice>price.getPrice()){
					minPrice = price.getPrice();
				}
				if(maxPrice<price.getPrice()){
					maxPrice = price.getPrice();
				}
			}
		}
		goodsVO.setMinPrice(minPrice);
		goodsVO.setMaxPrice(maxPrice);
		goodsVO.setSizePrice(sizePriceList);
		return goodsVO;
	}
	
	public List<Map<String, Object>> getNewGroupGoodsList(List<Map<String, Object>> groupGoodsList, List<Map<String, Object>> goodsList){
		
		List<Map<String, Object>> newGoodsList = new ArrayList<Map<String,Object>>();
		if(Utils.isEmpty(goodsList)){
			return newGoodsList;
		}
		if(!Utils.isEmpty(goodsList) && Utils.isEmpty(groupGoodsList)){
			return goodsList;
		}
		for(Map<String, Object> goodsMap : goodsList){
			for(Map<String, Object> groupGoodsMap : groupGoodsList){
				if(!Utils.isEmpty(groupGoodsMap.get("goodsId")) && !Utils.isEmpty(goodsMap.get("goodsId"))
						&& Integer.valueOf(groupGoodsMap.get("goodsId").toString()).equals(Integer.valueOf(goodsMap.get("goodsId").toString()))){
					if(!Utils.isEmpty(groupGoodsMap.get("sizeId")) 
							&& Long.valueOf(groupGoodsMap.get("sizeId").toString()).equals(Long.valueOf(goodsMap.get("sizeId").toString()))){
						if(!Utils.isEmpty(groupGoodsMap.get("price"))){
							goodsMap.put("price", Double.valueOf(groupGoodsMap.get("price").toString()));
						}
					}
					newGoodsList.add(goodsMap);
					continue;
				}
			}
		}
		return newGoodsList;
	}
}